// pages/index/index.js
var app = getApp(); //获取应用实例
const quote = app.globalData.quote;
const mta = quote.mta;
const util = quote.util;
const tools = quote.tools;
const api = quote.api;
const path = quote.paths;
const DataStorage = quote.DataStorage;
const Authorize = quote.Authorize;
const localData = quote.localData;
// console.log('localData', localData)

Page({
    data: {
        path: path,
        loginStatus: false, //登录状态
        isPromptClose: true,
        dub_num: 0,
        dailyUpdate: {},
        videoUrl: app.globalData.videoUrl,
        labelsArr: localData.labelsArr,
        label_id: 0,
        labelVideos: localData.labelVideos,
        DailyUpdatesList: [], //每日更新数据
        HotRecommendationList: [], //热门推荐数据
        CategoryListList: [], //视频分类数据源
        VideoCategory: [], //当前显示视频分类数据
        changeIndex: 2, //当前分类视频的编号
        thisDay: "",
        hideModal: false,
        hidePop: true,
        hideplaysIntroduction: true,
        isFirst: true,
        loadingHidden: false,
        Dailychallenge: 1, //是否为挑战视频
        scaleH: app.globalData.scaleH || 1,
        DefaultTimes: 0, //每日挑战的默认练习次数
        AccountsTimes: 0, //账户中获取的练习次数
        hideloadmore: true,
        activity: [],
        nodata: false,
        showWebview: false,
        console: console.log('打印首页数据', app),
        scopeUserInfo: false,
    },
    //事件处理函数
    onLoad: function(obj) {
        var self = this

        mta.Page.init();

        console.log('onload，首页加载', obj)

        //显示当前页面的转发按钮
        wx.showShareMenu({
                withShareTicket: true,
                success: function(res) {
                    console.log('显示页面的转发按钮', res);
                }
            })
            // self.DataStorage = new DataStorage(app);
    },

    onShow: function(obj) {
        var self = this;

        console.log('onshow，首页显示', obj)

        var activity = localData.activity.slice();
        if (app.globalData.deviceInfo.model.indexOf('iPhone') == 0) {
            activity.splice(2, 1)
        }
        console.log('loginstatus', app.globalData.loginStatus)
        setTimeout(() => {
            self.setData({
                loginStatus: app.globalData.loginStatus,
                AlreadyPracticed: app.globalData.AlreadyPracticed,
                hidePop: true,
                activity: activity
            })
        }, 500);
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function(obj) {
        var that = this

        console.log('onReady，初次渲染完成', obj)
        that.getWeekDay(); //获取日期
        that.GetWechatIndexPage(); //获取首页数据
        that.authorizePop = that.selectComponent('#authorizePop')
    },

    onHide: function() {
        var that = this;
    },
    //下拉刷新
    onPullDownRefresh: function(params) {
        var that = this;

        that.GetWechatIndexPage(null, function(params) {
            //数据加载完后停止刷新
            setTimeout(() => {
                console.log('停止刷新');
                wx.stopPullDownRefresh();
                that.setData({
                    changeIndex: 2,
                    hideloadmore: true,
                })
            }, 1000);
        })
    },
    //上拉触底事件
    onReachBottom: function(e) {
        // 页面上拉触底事件的处理函数
        var that = this;
        console.log('页面到底了', e);

        if (that.data.label_id == 0) {
            var VideoCategory = that.data.VideoCategory; //页面显示视频分类数据
            var CategoryListList = that.data.CategoryListList; //所有视频分类数据
            var changeIndex = that.data.changeIndex; //分类视频编号
            if (changeIndex >= CategoryListList.length) {
                that.setData({
                    hideloadmore: false,
                })
                return
            }

            VideoCategory.push(CategoryListList[changeIndex]);
            CategoryListList[changeIndex + 1] && VideoCategory.push(CategoryListList[changeIndex + 1]);

            wx.showLoading({
                title: '加载中...',
            });
            setTimeout(() => {
                that.setData({
                    VideoCategory: VideoCategory,
                    changeIndex: changeIndex + 2
                })
                wx.hideLoading();
            }, 500);
        } else {
            var labelVideos = that.data.labelVideos;
            var arr = localData.labelVideos.QuestionList;
            var label_index = that.data.label_index || 0;

            if (label_index >= 3) {
                that.setData({
                    hideloadmore: false,
                })
                return
            }

            labelVideos.QuestionList = labelVideos.QuestionList ? labelVideos.QuestionList.concat(arr) : [].concat(arr);

            wx.showLoading({
                title: '加载中...',
            });
            setTimeout(() => {
                that.setData({
                    labelVideos: labelVideos,
                    label_index: label_index + 1
                })
                wx.hideLoading();
            }, 500);
        }
    },

    //分享事件
    onShareAppMessage: function(res) {

        console.log('转发事件', res);

        app.aldstat.sendEvent('首页-点击右上转发');
        mta.Event.stat("home_clicktransmit", {});

        return {
            title: '邀你进入口语殿堂，挑战登顶共赢现金红包',
            desc: '天天口语秀',
            path: '/' + path.index,
            success: function(res) {
                console.log('转发成功', res);
                wx.showShareMenu({
                    // 要求小程序返回分享目标信息
                    withShareTicket: true
                });
            },
            fail: function(err) {
                console.log('转发失败', err)
            }
        }
    },

    //加载首页数据
    GetWechatIndexPage: function(params, cb) {
        var that = this;

        var dataDic = {
            openid: app.globalData.openId
        }
        api.methodGetWechatIndexPage({
            dataDic: dataDic,
            complete: function(res) {
                console.log(res.data)
                if (res.data.code != 0) {
                    wx.showModal({
                        title: '温馨提示',
                        showCancel: false,
                        content: res.data.msg || "数据请求失败",
                    })
                    return;
                } else {
                    that.setData({
                        DailyUpdatesList: res.data.data.DailyUpdatesList,
                        HotRecommendationList: res.data.data.HotRecommendationList,
                        CategoryListList: res.data.data.CategoryListList,
                        VideoCategory: [res.data.data.CategoryListList[0], res.data.data.CategoryListList[1]],
                        loadingHidden: true,
                    })
                }
                // that.DataStorage._downLoadFile(['https://admin.acadsoc.com.cn/uploads/IESVideo/Cover/20180316/ee8ed4f5-04b6-4d13-85ea-5adc25c2db6f.jpg', 'https://ies.acadsoc.com.cn/uploads/voice/Official/20180202/fb7068d2-fb2c-4497-a87a-41f115e3deb9.mp3', 'https://video.acadsoc.com.cn/iesfiles/video/20180316/50309570-e384-4444-b51a-8f6e0e07303f.mp4'])
                typeof cb == 'function' && cb(res)
            }
        })
    },
    imgOnLoad(e) { //图片加载
        var that = this;

        // console.log('图片加载完成', e);
        const obj = e.currentTarget.dataset.obj;
        if (e.detail.height) {
            that.setData({
                [obj]: true
            })
        }
    },

    //活动入口
    activityEntrance: function(e) {
        var that = this;

        console.log('e', e)
        var activityData = e.currentTarget.dataset.activitydata; //获取活动数据
        var userObj = e.detail;
        var getUserInfo = userObj.errMsg.split(':');
        // console.log('activityData', activityData)

        app.aldstat.sendEvent('首页-点击进入活动', { 'activityid': activityData.activityID });
        mta.Event.stat("home_clickentryactivity", { 'activityid': activityData.activityID });

        if (getUserInfo[1] != 'ok') {
            console.log('getUserInfo[1]', getUserInfo[1])
            Authorize.checkUserInfo(function(res) {
                    if (!res) {
                        that.setData({
                            hidePop: false
                        })
                    } else {
                        that.setData({
                            hidePop: true
                        })
                    }
                }) //进入授权流程
            return
        } else {
            app.globalData.userInfo = userObj.userInfo; //用户信息存入全局
            wx.setStorage({
                key: 'userInfo',
                data: userObj.userInfo,
                success: function(res) {
                    console.log('用户信息存入缓存成功', res)
                }
            })
            gotoActivity();
        }

        function gotoActivity() {
            switch (activityData.activityID) {
                case 1:
                    //进入活动页
                    wx.navigateTo({
                        url: `/${activityData.path}`,
                    })
                    break;
                case 2:
                    //进入H5页面
                    console.log(activityData.path)
                    wx.navigateTo({
                        url: `/${path.h5}?webUrl=${activityData.webUrl}`,
                    })
                    break;
                case 3:
                    //跳转到新的小程序
                    console.log('跳转到新的小程序')
                    wx.navigateToMiniProgram({
                        appId: activityData.appId,
                        path: activityData.path,
                        extraData: {

                        },
                        envVersion: 'release',
                        success(res) {
                            // 打开成功
                            console.log('跳转到新的小程序成功')
                        }
                    })
                    break;
            }
        }

    },

    //换一换
    tapExchange: function(e) {
        var self = this

        wx.showLoading({
            title: '加载中...',
        })

        console.log('tapExchange', e)
        var categoryid = e.currentTarget.dataset.categoryid;

        app.aldstat.sendEvent('首页-点击换一换', { 'categoryid': categoryid });
        mta.Event.stat("home_clickexchange", { 'categoryid': categoryid });

        var dataDic = {
            openid: app.globalData.openId,
            CategoryId: categoryid
        }

        api.methodCategoryChangeOneChange({
            dataDic,
            success: (res) => {
                console.log(res.data)
                if (res.data.code != 0) {
                    wx.showModal({
                        title: '温馨提示',
                        showCancel: false,
                        content: res.data.msg || "数据请求失败",
                    })
                    return;
                } else {
                    var VideoCategory = self.data.VideoCategory;
                    for (let index = 0; index < VideoCategory.length; index++) {
                        var ele = VideoCategory[index];
                        if (ele['CategoryId'] == categoryid) {
                            console.log('ele', ele)
                            ele['QuestionList'] = res.data.data
                        }
                    }
                    self.setData({
                        VideoCategory: VideoCategory,
                    })
                }
            },
            fail: (res) => {
                console.log(res);
            },
            complete: (res) => {
                wx.hideLoading();
                console.log(res.data);
            }
        });
    },

    lookMore: function(e) {
        var that = this;

        var userObj = e.detail
        var getUserInfo = userObj.errMsg.split(':')

        if (getUserInfo[1] != 'ok') {
            Authorize.checkUserInfo(function(res) {
                    if (!res) {
                        that.setData({
                            hidePop: false
                        })
                    } else {
                        that.setData({
                            hidePop: true
                        })
                    }
                }) //进入授权流程
            return
        } else {
            app.globalData.userInfo = userObj.userInfo; //用户信息存入全局
            wx.setStorage({
                key: 'userInfo',
                data: userObj.userInfo,
                success: function(res) {
                    console.log('用户信息存入缓存成功', res)
                }
            })
        }

        var loginStatus = app.globalData.loginStatus;
        if (loginStatus) {
            app.aldstat.sendEvent('首页-每日推荐-点击查看更多（已登录）');
            mta.Event.stat("home_clicklookmore_login", {});
            wx.navigateTo({
                url: '/' + path.dailyRecommend
            })
        } else {
            app.aldstat.sendEvent('首页-每日推荐-点击查看更多（未登录）');
            mta.Event.stat("home_clicklookmore_notlogin", {});
            wx.navigateTo({
                url: '/' + path.login
            })
        }
    },

    //去下一页
    getuserinfo(params) {
        var that = this

        console.log('点击下一页', params);
        var isjoin = params.currentTarget.dataset.isjoin;
        var location = params.currentTarget.dataset.location;
        var qid = params.currentTarget.dataset.qid;
        var type = params.currentTarget.dataset.type;
        var userObj = params.detail;
        var getUserInfo = userObj.errMsg.split(':');

        var aldStr = "首页-点击"
        mta.Event.stat("home_click")

        if (location == 0) {
            aldStr = "首页-点击每日一句";
            mta.Event.stat("home_clickdailysentence");
        } else {
            aldStr = "首页-点击-" + type + "-" + location;
            var hotNumber = "home_click_hot";
            mta.Event.stat(hotNumber, { 'classify': type, 'location': location });
        }
        console.log('aldStr', aldStr);
        app.aldstat.sendEvent(aldStr, { 'classify': type });

        if (getUserInfo[1] != 'ok') {
            Authorize.checkUserInfo(function(res) {
                    if (!res) {
                        that.setData({
                            hidePop: false
                        })
                    } else {
                        that.setData({
                            hidePop: true
                        })
                    }
                }) //进入授权流程
            return
        } else {
            app.globalData.userInfo = userObj.userInfo; //用户信息存入全局
            wx.setStorage({
                key: 'userInfo',
                data: userObj.userInfo,
                success: function(res) {
                    console.log('用户信息存入缓存成功', res)
                }
            })
            if (isjoin == 1 || app.globalData.AlreadyPracticed[qid]) {
                wx.navigateTo({
                    url: '/' + path.scorePreview + '?QID=' + qid
                })
            } else {
                wx.navigateTo({
                    url: '/' + path.details + '?QID=' + qid
                })
            }
        }

    },

    aldClickRegist: function(e) {
        app.aldstat.sendEvent('首页-点击立即注册（弹窗）');
        mta.Event.stat("home_clickregisterpopup", {});
    },

    //获取星期日期
    getWeekDay: function() {
        var self = this
        var nowDate = new Date();
        var week = nowDate.getDay()
        var month = nowDate.getMonth() + 1
        var str = nowDate.getFullYear() + "-" + month + "-" + nowDate.getDate();

        self.setData({
            thisDay: str
        })

    },

    //收集formId
    saveFormId: tools.saveFormId,

    //关闭模态框
    cancel: function() {
        var that = this;

        app.aldstat.sendEvent('首页-点击关闭大的注册弹窗');
        mta.Event.stat("home_clickcloseregisterpopup", {});

        that.setData({
            hideModal: true,
            isPromptClose: false,
        })
    },
    //点击注册banner
    clickRegistBanner: function() {
        app.aldstat.sendEvent('首页-点击小的注册banner');
        mta.Event.stat("home_clickregisterbanner", {});
    },
    //关闭悬浮提示框
    close: function() {
        var that = this;

        app.aldstat.sendEvent('首页-点击关闭小的注册banner');
        mta.Event.stat("home_closeregisterbanner", {});

        that.setData({
            isPromptClose: true
        })
    },

    //取消按钮被点击
    onCancelTap: function(e) {
        var that = this;

        console.log('取消按钮已点击', e);

        that.setData({
                hidePop: true
            })
            // wx.navigateBack({
            //     delta: 1, // 回退前 delta(默认为1) 页面
            // })
    },

    //确定按钮被点击
    onConfirmTap(e) {
        var that = this;

        console.log('确定按钮已点击', e);
        var type = e.detail.type;
        var detail = e.detail.detail;
        if (type == 'getUserInfo') {

        } else if (type == 'openSetting') {

        }
    },

    //点击标签
    tapLabel(e) {
        var that = this;

        console.log('标签已点击', e);
        var id = e.currentTarget.dataset.id
        that.setData({
            // labelsArr: '',
            label_id: id,
            labelVideos: {},
            label_index: 0,
        })
    }
})